package cn.com.zaprk.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @PackageName: cn.com.zaprk.jdbc
 * @ClassName: JDBC_05
 * @Description: JDBC操作DML， insert  update  delete
 * @author: RZS
 * @date: 2021/10/20  17:50
 */
public class JDBC_05_Insert {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stat = null;
        try {
            // 1、注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2、获取连接
            conn = DriverManager.getConnection("jdbc:mysql:///mydb1", "root", "root");
            // 3、创建Statement对象，用于执行sql
            stat = conn.createStatement();
            // 4、编写sql
            //String sql = "insert into user(name,money) values('张三', 1000.0),('李四', 3000.0),('王五', 5000.0)";
            System.out.println("*******************批量插入数据开始******************");
            String sql1 = "insert into user(name,money) values('张三1', 10000.0)";
            String sql2 = "insert into user(name,money) values('张三2', 100000.0)";
            String sql3 = "insert into user(name,money) values('张三3', 1000000.0)";

            // 将sql添加到缓冲区
            //stat.executeUpdate(sql1);
            stat.addBatch(sql1);
            stat.addBatch(sql2);
            stat.addBatch(sql3);

            System.out.println("*******************批量插入数据结束  EDN ******************");

            // 5、执行sql
            //stat.execute(sql);
            // 批量执行sql语句
            int[] ints = stat.executeBatch();
            System.out.println(ints.length);
            // 6、获取sql执行结果
            System.out.println("插入数据表完成");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 7、关闭连接
            if (stat != null) {
                try {
                    stat.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
